﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>供应商管理</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
    <div class="layui-card">
        <div class="layui-card-header">
            <h2>供应商管理</h2>
        </div>
        <div class="layui-card-body">
            <!-- 查询表单 -->
            <form class="layui-form" id="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <input type="text" name="keyword" placeholder="请输入供应商名称/编码" class="layui-input" />
                    </div>
                    <div class="layui-col-md2">
                        <select name="isEnabled">
                            <option value="">是否启用</option>
                            <option value="true">是</option>
                            <option value="false">否</option>
                        </select>
                    </div>
                    <div class="layui-col-md2">
                        <button type="button" class="layui-btn" id="searchBtn">搜索</button>
                        <button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                    </div>
                </div>
            </form>
            <!-- 操作按钮 -->
            <div style="margin:10px 0;">
                <button class="layui-btn" id="addBtn">新增</button>
                <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">批量删除</button>
            </div>
            <!-- 数据表格 -->
            <table class="layui-table" id="supplierTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="checkAll" /></th>
                        <th>编码</th>
                        <th>名称</th>
                        <th>等级</th>
                        <th>评分</th>
                        <th>电话</th>
                        <th>是否启用</th>
                        <th>地址</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <!-- 数据通过JS渲染 -->
                </tbody>
            </table>
            <!-- 分页 -->
            <div id="pagination"></div>
        </div>
    </div>
    <!-- 新增/编辑弹窗（可用Layui弹窗实现） -->
    <div id="editModal" style="display:none;">
        <form class="layui-form" id="editForm" lay-filter="editForm">
            <input type="hidden" name="Id" />
            <div class="layui-form-item">
                <label class="layui-form-label">供应商编码</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline" style="width: 280px;">
                        <input type="text" name="SupplierCode" id="supplierCodeInput" class="layui-input" required />
                    </div>
                    <div class="layui-input-inline" id="autoGenerateRow">
                        <input type="checkbox" id="autoGenerateSwitch" lay-skin="switch" lay-filter="autoGenerate" lay-text="自动生成|手动输入">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">供应商名称</label>
                <div class="layui-input-block">
                    <input type="text" name="SupplierName" class="layui-input" required />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">供应商等级</label>
                <div class="layui-input-block">
                    <input type="text" name="SupplierGrade" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">供应商评分</label>
                <div class="layui-input-block">
                    <input type="number" name="SupplierScore" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">供应商电话</label>
                <div class="layui-input-block">
                    <input type="text" name="SupplierPhone" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否启用</label>
                <div class="layui-input-block">
                    <input type="radio" name="IsNo" value="1" title="是" />
                    <input type="radio" name="IsNo" value="0" title="否" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地址</label>
                <div class="layui-input-block">
                    <input type="text" name="SupplierAdress" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <input type="text" name="Context" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelEdit">取消</button>
            </div>
        </form>
    </div>
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.all.js"></script>
    <script>
        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;

            // 分页参数
            var currentPage = 1;
            var pageSize = 10;

            // 加载数据
            function loadSuppliers() {
                var keyword = $('input[name="keyword"]').val();
                var isEnabled = $('select[name="isEnabled"]').val();
                $.ajax({
                    url: '/Supplier/GetSupplierPagedList/GetSupplierPagedListAsync',
                    type: 'GET',
                    data: {
                        keyword: keyword,
                        isEnabled: isEnabled,
                        page: currentPage,
                        pageSize: pageSize
                    },
                    dataType: 'json',
                    success: function (res) {
                        renderTable(res.data);
                        renderPagination(res.total);
                    }
                });
            }

            // 渲染表格
            function renderTable(data) {
                var html = '';
                if (!data || data.length === 0) {
                    html = '<tr><td colspan="10" style="text-align:center;">暂无数据</td></tr>';
                } else {
                    data.forEach(function (item) {
                        html += `
                        <tr>
                            <td><input type="checkbox" class="row-check" value="${item.id}"></td>
                            <td>${item.supplierCode || ''}</td>
                            <td>${item.supplierName || ''}</td>
                            <td>${item.supplierGrade || ''}</td>
                            <td>${item.supplierScore || 0}</td>
                            <td>${item.supplierPhone || ''}</td>
                            <td>${item.isNo == 1 ? '是' : '否'}</td>
                            <td>${item.supplierAdress || ''}</td>
                            <td>${item.context || ''}</td>
                            <td>
                                <a href="javascript:;" class="edit-btn" data-id="${item.id}">修改</a>
                                <a href="javascript:;" class="delete-btn" data-id="${item.id}">删除</a>
                            </td>
                        </tr>`;
                    });
                }
                $('#tableBody').html(html);
            }

            // 渲染分页
            function renderPagination(total) {
                var pageCount = Math.ceil(total / pageSize);
                var html = '';
                if (pageCount > 1) {
                    html += `<button ${currentPage == 1 ? 'disabled' : ''} onclick="gotoPage(${currentPage - 1})">&lt;</button>`;
                    for (var i = 1; i <= pageCount; i++) {
                        html += `<button ${i == currentPage ? 'style="font-weight:bold;"' : ''} onclick="gotoPage(${i})">${i}</button>`;
                    }
                    html += `<button ${currentPage == pageCount ? 'disabled' : ''} onclick="gotoPage(${currentPage + 1})">&gt;</button>`;
                }
                $('#pagination').html(html);
            }

            // 分页跳转
            window.gotoPage = function (page) {
                currentPage = page;
                loadSuppliers();
            };

            // 查询按钮
            $('#searchBtn').click(function () {
                currentPage = 1;
                loadSuppliers();
            });

            // 重置按钮
            $('#resetBtn').click(function () {
                $('#searchForm')[0].reset();
                form.render('select');
                setTimeout(loadSuppliers, 100);
            });

            // 自动生成编码开关
            form.on('switch(autoGenerate)', function (data) {
                var input = $('#supplierCodeInput');
                if (data.elem.checked) {
                    // 生成并设置编码
                    var date = new Date();
                    var year = date.getFullYear();
                    var month = ('0' + (date.getMonth() + 1)).slice(-2);
                    var day = ('0' + date.getDate()).slice(-2);
                    var hours = ('0' + date.getHours()).slice(-2);
                    var minutes = ('0' + date.getMinutes()).slice(-2);
                    var seconds = ('0' + date.getSeconds()).slice(-2);
                    var code = 'SUP' + year + month + day + hours + minutes + seconds;
                    input.val(code);
                    input.prop('readonly', true);
                } else {
                    // 清空编码并使其可编辑
                    input.val('');
                    input.prop('readonly', false);
                }
            });

            // 新增按钮
            $('#addBtn').click(function () {
                $('#editForm')[0].reset();
                $('#supplierCodeInput').prop('readonly', false); // 解除只读
                form.val('editForm', { Id: 0 }); // 设置ID为0，并清空表单

                // 确保自动生成开关可见并处于关闭状态
                $('#autoGenerateRow').show();
                $('#autoGenerateSwitch').prop('checked', false);

                layer.open({
                    type: 1,
                    title: '新增供应商',
                    area: ['600px', 'auto'],
                    content: $('#editModal'),
                    success: function() {
                        form.render(); // 重新渲染弹窗中的表单，包括开关
                    }
                });
            });

            // 编辑按钮
            $(document).on('click', '.edit-btn', function () {
                var id = $(this).data('id');
                $.get('/Supplier/GetSupplierById/GetSupplierByIdAsync', { id: id }, function (res) {
                    if (res) {
                        // 手动映射数据，解决大小写不匹配问题
                        var formData = {
                            Id: res.id,
                            SupplierCode: res.supplierCode,
                            SupplierName: res.supplierName,
                            SupplierGrade: res.supplierGrade,
                            SupplierScore: res.supplierScore,
                            SupplierPhone: res.supplierPhone,
                            IsNo: res.isNo,
                            SupplierAdress: res.supplierAdress,
                            Context: res.context
                        };

                        // 编辑时，编码只读，并隐藏自动生成开关
                        $('#supplierCodeInput').prop('readonly', true);
                        $('#autoGenerateRow').hide();

                        // 使用 form.val() 自动返填数据
                        form.val('editForm', formData);
                        layer.open({
                            type: 1,
                            title: '编辑供应商',
                            area: ['600px', 'auto'],
                            content: $('#editModal'),
                            success: function() {
                                form.render(); // 重新渲染，特别是radio
                            }
                        });
                    } else {
                        layer.msg('获取供应商信息失败', { icon: 2 });
                    }
                });
            });

            // 保存
            form.on('submit(save)', function (data) {
                var formData = data.field;
                $.ajax({
                    url: '/Supplier/SaveSupplier/SaveSupplierAsync',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function (res) {
                        if (res) {
                            layer.msg('保存成功', { icon: 1 });
                            layer.closeAll();
                            loadSuppliers();
                        } else {
                            layer.msg('保存失败', { icon: 2 });
                        }
                    }
                });
                return false;
            });

            // 取消编辑
            $('#cancelEdit').click(function () {
                layer.closeAll();
            });

            // 删除
            $(document).on('click', '.delete-btn', function () {
                var id = $(this).data('id');
                layer.confirm('确定要删除该供应商吗？', function (index) {
                    $.post('/Supplier/DeleteSupplier/DeleteSupplierAsync', { id: id }, function (res) {
                        if (res) {
                            layer.msg('删除成功', { icon: 1 });
                            loadSuppliers();
                        } else {
                            layer.msg('删除失败', { icon: 2 });
                        }
                    });
                    layer.close(index);
                });
            });

            // 批量删除
            $('#batchDeleteBtn').click(function () {
                var ids = [];
                $('.row-check:checked').each(function () {
                    ids.push($(this).val());
                });
                if (ids.length === 0) {
                    layer.msg('请先选择要删除的供应商');
                    return;
                }
                layer.confirm('确定要批量删除选中的供应商吗？', function (index) {
                    $.ajax({
                        url: '/Supplier/DeleteSupplierBatch/DeleteSupplierBatchAsync',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        success: function (res) {
                            if (res) {
                                layer.msg('删除成功', { icon: 1 });
                                loadSuppliers();
                            } else {
                                layer.msg('删除失败', { icon: 2 });
                            }
                        }
                    });
                    layer.close(index);
                });
            });

            // 全选
            $('#checkAll').on('change', function () {
                $('.row-check').prop('checked', this.checked);
            });

            // 首次加载
            loadSuppliers();
        });
    </script>
</body>
</html>